package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

   @Autowired
   private RoleDao roleDao;

   @Autowired
   private AdminRoleDao adminRoleDao;

   @Override
   public List<Role> findAll() {
      return roleDao.findAll();
   }

   @Override
   public Map<String, Object> findRoleByAdminId(Long adminId) {
      //查询所有的角色
      List<Role> allRoleList = roleDao.findAll();
      //拥有角色的id
      List<Long> exitRoleIdList =  adminRoleDao.findRoleByAdminId(adminId);
      //对角色进行分类
      List<Role> noAssignRoleList = new ArrayList<>();
      List<Role> assignRoleList = new ArrayList<>();
      for (Role role:allRoleList){
         //已分配
         if (exitRoleIdList.contains(role.getId())){
            assignRoleList.add(role);
         }else {
            noAssignRoleList.add(role);
         }
      }
      Map<String,Object> roleMap = new HashMap<>();
      roleMap.put("noAssignRoleList",noAssignRoleList);//noAssignRoleList
      roleMap.put("assignRoleList",assignRoleList);//assignRoleList

      return roleMap;
   }

   @Override
   public void saveUserRoleRealtionShip(Long adminId, Long[] roleIds) {
      adminRoleDao.deleteByAdminId(adminId);
      for (Long roleId:roleIds){
         if (StringUtils.isEmpty(roleId)){
            continue;
         }
         AdminRole userRole = new AdminRole();
         userRole.setAdminId(adminId);
         userRole.setRoleId(roleId);
         adminRoleDao.insert(userRole);
      }
   }

   @Override
   public BaseDao<Role> getEntityDao() {
      return roleDao;
   }

}